package com.keter.framework.web.component.sequence;

import com.alibaba.fastjson.JSONObject;
import com.keter.framework.web.component.sequence.core.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 全局唯一ID生成组件: 必须在单例模式下使用
 * Sequence出处： https://gitee.com/yu120/sequence.git
 * Created by shadowedge on 2018/11/23.
 */
@Component
public class Sequencer {

    @Value("${sid.dataCenterId:#{1}}")
    private int dataCenterId;

    @Value("${sid.workerId:#{1}}")
    private int workerId;

    private Sequence sequence;
    private Decoder decoder;

    @Autowired
    private void init(){
        sequence = new Sequence(dataCenterId);
        //使用sequence参数初始化decoder
        decoder = new Decoder(Sequence.DATA_CENTER_ID_BITS, Sequence.WORKER_ID_BITS, Sequence.START_TIME);
    }

    public long genId(){
        return sequence.nextId().longValue();
    }

    public JSONObject decode(long id){
        return decoder.decode(id);
    }

    public static void main(String[] args) {

        Sequence sequence = new Sequence(1);
        for (int i = 0; i < 100; i++) {
            Long id = sequence.nextId();
//            System.out.println(id);
            int code = id.hashCode();
            System.out.println(code);
            //0~99
            System.out.println(code & 0xff);
            //0~999
            System.out.println(code & 0xff);
        }
    }

}
